/**
 * @description:
 * @author: 梅雄
 * @createDate: 2021/8/26
 * @version: 1.0
 * @status: done
 */
package com.xhwl.centiotdata.suppliersystem.eesd.batown;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description:
 * @Copyright: Copyright (c) 2021  ALL RIGHTS RESERVED.
 * @Company: 深圳兴海物联科技有限公司
 * @Author: 梅雄
 * @CreateDate: 2021/8/26 17:16
 * @UpdateDate: 2021/8/26 17:16
 * @UpdateRemark: init
 * @Version: 1.0
 * @menu
 */
@Slf4j
public class BaAccessUtil {

    private static String host;

    private static String appId;

    private static String token;

    private static String loginProjectId;

    /**
     * 请求超时时间，单位毫秒
     */
    private static final int TIME_OUT = 20 * 1000;

    public BaAccessUtil(String host1, String appId1, String token1) {
        host = host1;
        appId = appId1;
        token = token1;
    }
    public BaAccessUtil(String host1, String appId1, String token1,String loginProjectId1) {
        host = host1;
        appId = appId1;
        token = token1;
        loginProjectId = loginProjectId1;
    }

    /**
     * 32位MD5加密的大写字符串
     */
    private static String md5(String s) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断基本数据类型
     */
    private static boolean checkBasic(Object value) {
        Class[] cl = {
                String.class, int.class, double.class, char.class, long.class, short.class, boolean.class, byte.class,
                Integer.class, Double.class, Character.class, Long.class, Short.class, Boolean.class, Byte.class
        };
        for (Class aClass : cl) {
            if (aClass.isAssignableFrom(value.getClass())) {
                return true;
            }
        }
        return false;
    }

    /**
     * Map排序
     */
    private static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    /**
     * Map排序
     */
    private static class MapKeyComparator implements Comparator<String> {
        @Override
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }


    private static String getSign(Map<String, Object> map) {
        Map<String, Object> sortMap = sortMapByKey(map);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> stringObjectEntry : sortMap.entrySet()) {
            if (checkBasic(stringObjectEntry.getValue())) {
                sb.append(stringObjectEntry.getValue());
            } else {
                sb.append(JSON.toJSONString(stringObjectEntry.getValue(), SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteMapNullValue));
            }
        }
        sb.append(token);
        log.info("-------sb:{}",sb);
        return md5(sb.toString());
    }

    private static String post(String url, Map<String, Object> map) {
        return HttpUtil.post(url, map, TIME_OUT);
    }

    /**
     * 获取临时TOKEN
     */
    private <T> T getTempToken() {
        long time = System.currentTimeMillis();
        String url = host + "Authorize/GetToken";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("appid", appId);
        map.put("timestamp", time);
        map.put("sign", getSign(map));
        String result = post(url, map);
        return JSON.parseObject(result, new TypeReference<T>() {
        });
    }


    /**
     * 获取站点单元树
     */
    public <T> T getSiteTree() {
        long time = System.currentTimeMillis();
        String url = host + "SiteUnit/GetSiteUnitTree";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("appid", appId);
        map.put("projectId",loginProjectId);
        map.put("timestamp", time);
        map.put("sign", getSign(map));
        String result = post(url, map);
        return JSON.parseObject(result, new TypeReference<T>() {
        });
    }

    /**
     * 获取站点单元详细信息
     */
    public <T> T getSiteTreeDetail(String id) {
        //获取住院楼一楼 ddcz_1f_3的详情
        long time = System.currentTimeMillis();
        String url = host + "SiteUnit/GetSiteUnitInfo";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("appid", appId);
        map.put("id", id);
        map.put("timestamp", time);
        map.put("sign", getSign(map));
        String result = post(url, map);
        return JSON.parseObject(result, new TypeReference<T>() {
        });
    }

    /**
     * 执行站点单元方法
     */
    private <T> T execuMethod() {
        //住院楼一楼 ddcz_1f_3 季节切换操作
        long time = System.currentTimeMillis();
        String url = host + "SiteUnit/InvokeMethod";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("appid", appId);
        map.put("id", "398076b0454c463e8c4780ed95be1b8a");
        map.put("method", "SEASONAL_SWITCH");
        map.put("params", "{\"Value\":true}");
        map.put("timestamp", time);
        map.put("sign", getSign(map));
        String result = post(url, map);
        return JSON.parseObject(result, new TypeReference<T>() {
        });
    }


    /**
     * 查询标签历史时段数据
     */
    private <T> T queryLabelDateHistory() {
        //住院楼一楼 ddcz_1f_3 季节切换操作
        long time = System.currentTimeMillis();
        String url = host + "RTDB/QueryHistoryData";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("appid", appId);
        map.put("tags", "");
        map.put("startTime", "2021-08-01 00:00:00");
        map.put("endTime", "2021-09-01 00:00:00");
        map.put("interval", 0);
        map.put("timestamp", time);
        map.put("sign", getSign(map));
        String result = post(url, map);
        return JSON.parseObject(result, new TypeReference<T>() {
        });
    }

    /**
     * 查询标签历史数据
     */
    private <T> T queryLabelCountHistory() {
        //住院楼一楼 ddcz_1f_3 季节切换操作
        long time = System.currentTimeMillis();
        String url = host + "RTDB/QueryLastData";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("appid", appId);
        map.put("tags", "");
        map.put("time", "2021-08-01 00:00:00");
        map.put("count", 1);
        map.put("timestamp", time);
        map.put("sign", getSign(map));
        String result = post(url, map);
        return JSON.parseObject(result, new TypeReference<T>() {
        });
    }

    /**
     * 查询标签
     */
    private <T> T queryLabel() {
        //住院楼一楼 ddcz_1f_3 季节切换操作
        long time = System.currentTimeMillis();
        String url = host + "RTDB/QueryTags";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("appid", appId);
        map.put("tags", "449300b6f2a144eab2338b6b8e616f8a");
        map.put("timestamp", time);
        map.put("sign", getSign(map));
        String result = post(url, map);
        return JSON.parseObject(result, new TypeReference<T>() {
        });
    }
}

